package com.lc.tgxm.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.lc.tgxm.R;
import com.lc.tgxm.conn.UpicAsyPost;
import com.lc.tgxm.dialog.MProgressDialog;
import com.lc.tgxm.model.User;
import com.lc.tgxm.util.Log;
import com.lc.tgxm.util.UtilPermission;
import com.zcx.helper.entity.AppCrop;
import com.zcx.helper.http.AsyCallBack;

import java.io.File;

/**
 * OneActivity
 * Created by Lei on 2016/12/30.
 */
public class OneActivity extends BasePicActivity {
    private WebView wv;
    /**
     * Android 5.0以下版本的文件选择回调
     */
    protected ValueCallback<Uri> mFileUploadCallbackFirst;
    /**
     * Android 5.0及以上版本的文件选择回调
     */
    protected ValueCallback<Uri[]> mFileUploadCallbackSecond;
    protected static final int REQUEST_CODE_FILE_PICKER = 51426;
    protected String mUploadableFileTypes = "image/*";
    private Handler mHandler = new Handler();
    private int jstype = 1;
    //    private static final String HOMEURL = "http://tongchenggzp.com/3g";
    private static final String HOMEURL = "file:///android_asset/echartsindex.html";
    private MProgressDialog dialog;
    private ImageView ivLoading;
    private TextView tvLoading;


    @Override
    @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"})
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);

        UtilPermission.Permission(this, Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        JSKit js = new JSKit(this);

        dialog = new MProgressDialog(this);
        ivLoading = (ImageView) findViewById(R.id.iv_loading);
        tvLoading = (TextView) findViewById(R.id.tv_loading);
//        Glide.with(OneActivity.this).load(R.drawable.loading2).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivLoading);

        wv = (WebView) findViewById(R.id.wv_main);
        wv.getSettings().setDomStorageEnabled(true);

        //设置参数
//        wv.getSettings().setBuiltInZoomControls(true);
        //内容的渲染需要webviewChromClient去实现，设置webviewChromClient基类，解决js中alert不弹出的问题和其他内容渲染问题
//        wv.setWebChromeClient(new OpenFileChromeClient());
        wv.getSettings().setJavaScriptEnabled(true);
        //把js绑定到全局的myjs上，myjs的作用域是全局的，初始化后可随处使用
        wv.addJavascriptInterface(js, "myjs");
        wv.setWebViewClient(new MyWebViewClient());
//        wv.loadUrl("http://app23.app.longcai.net/index.php/Wap/Home/index.html");
        wv.loadUrl(HOMEURL);
        wv.setWebChromeClient(new OpenFileChromeClient());

    }

    // 网络接口
    private UpicAsyPost upicAsyPost = new UpicAsyPost(new AsyCallBack<User>() {

        @Override
        public void onSuccess(String toast, int type, final User md) throws Exception {

            Log.e(TAG, "md", md.username);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    //调用 HTML 中的javaScript 函数
                    String strmsg;
                    if (jstype == 1) {
                        strmsg = "javascript:showMsg('" + md.username + "')";
                    } else {
                        strmsg = "javascript:showMsg2('" + md.username + "')";
                    }
                    Log.w(TAG, "strmsg", strmsg);
                    wv.loadUrl(strmsg);
                }
            });
        }

    });

    public void doActionForJs(int type) {
        Log.i(TAG, "type", type);
        this.jstype = type;
        startAlbum(null);
    }

    /**
     * 自定义WebView类，重载shouldOverrideUrlLoading，改变打开方式
     */
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            Log.e(TAG, "url", url);
//            int index_start = url.indexOf("word=");
//            int index_end = url.indexOf("&", index_start);
//            String keywords = url.substring(index_start, index_end);
//            Log.i(TAG, "keywords", keywords);
//            String kd = null;
//            try {
//                kd = URLDecoder.decode(keywords, "utf-8");
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//            Log.d(TAG, "kd", kd);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

//            dialog.show();
            ivLoading.setVisibility(View.VISIBLE);
            tvLoading.setVisibility(View.VISIBLE);
            tvLoading.postDelayed(textRunnable, 300);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
//            if (dialog.isShowing()) {
//                dialog.dismiss();
//            }
            ivLoading.setVisibility(View.GONE);
            tvLoading.setVisibility(View.GONE);
            tvLoading.removeCallbacks(textRunnable);
        }
    }

    private Runnable textRunnable = new Runnable() {
        @Override
        public void run() {
            String text = tvLoading.getText().toString();
            if (text.contains("...")) {
                tvLoading.setText(text.replace("...", ""));
            }
            tvLoading.append(".");
            tvLoading.postDelayed(textRunnable, 200);
        }
    };


    private class OpenFileChromeClient extends WebChromeClient {

        //  Android 2.2 (API level 8)到Android 2.3 (API level 10)版本选择文件时会触发该隐藏方法
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, null);
        }

        // Android 3.0 (API level 11)到 Android 4.0 (API level 15))版本选择文件时会触发，该方法为隐藏方法
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg, acceptType, null);
        }

        // Android 4.1 (API level 16) -- Android 4.3 (API level 18)版本选择文件时会触发，该方法为隐藏方法
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileInput(uploadMsg, null, false);
        }

        // Android 5.0 (API level 21)以上版本会触发该方法，该方法为公开方法
        @SuppressWarnings("all")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            if (Build.VERSION.SDK_INT >= 21) {
                final boolean allowMultiple = fileChooserParams.getMode() == FileChooserParams.MODE_OPEN_MULTIPLE;//是否支持多选


                openFileInput(null, filePathCallback, allowMultiple);

                return true;
            } else {
                return false;
            }
        }


    }

    @SuppressLint("NewApi")
    protected void openFileInput(final ValueCallback<Uri> fileUploadCallbackFirst, final ValueCallback<Uri[]> fileUploadCallbackSecond, final boolean allowMultiple) {
        //Android 5.0以下版本
        if (mFileUploadCallbackFirst != null) {
            mFileUploadCallbackFirst.onReceiveValue(null);
        }
        mFileUploadCallbackFirst = fileUploadCallbackFirst;

        //Android 5.0及以上版本
        if (mFileUploadCallbackSecond != null) {
            mFileUploadCallbackSecond.onReceiveValue(null);
        }
        mFileUploadCallbackSecond = fileUploadCallbackSecond;

        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);

        if (allowMultiple) {
            if (Build.VERSION.SDK_INT >= 18) {
                i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            }
        }

        i.setType(mUploadableFileTypes);

        startActivityForResult(Intent.createChooser(i, "选择文件"), REQUEST_CODE_FILE_PICKER);

    }

//    public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
//        Log.e(TAG, "onActivityResult");
//        if (requestCode == REQUEST_CODE_FILE_PICKER) {
//            if (resultCode == Activity.RESULT_OK) {
//                if (intent != null) {
//                    Log.w(TAG, "intent.getData()", intent.getData());
//                    Log.i(TAG, "getRealPathFromURI", getRealPathFromURI(intent.getData()));
//                    //Android 5.0以下版本
//                    if (mFileUploadCallbackFirst != null) {
//                        mFileUploadCallbackFirst.onReceiveValue(intent.getData());
//                        mFileUploadCallbackFirst = null;
//                    } else if (mFileUploadCallbackSecond != null) {//Android 5.0及以上版本
//                        Uri[] dataUris = null;
//
//                        try {
//                            if (intent.getDataString() != null) {
//                                dataUris = new Uri[]{Uri.parse(intent.getDataString())};
//                            } else {
//                                if (Build.VERSION.SDK_INT >= 16) {
//                                    if (intent.getClipData() != null) {
//                                        final int numSelectedFiles = intent.getClipData().getItemCount();
//
//                                        dataUris = new Uri[numSelectedFiles];
//
//                                        for (int i = 0; i < numSelectedFiles; i++) {
//                                            dataUris[i] = intent.getClipData().getItemAt(i).getUri();
//                                        }
//                                    }
//                                }
//                            }
//                        } catch (Exception ignored) {
//                        }
//                        mFileUploadCallbackSecond.onReceiveValue(dataUris);
//                        mFileUploadCallbackSecond = null;
//                    }
//                }
//            } else {
//                //这里mFileUploadCallbackFirst跟mFileUploadCallbackSecond在不同系统版本下分别持有了
//                //WebView对象，在用户取消文件选择器的情况下，需给onReceiveValue传null返回值
//                //否则WebView在未收到返回值的情况下，无法进行任何操作，文件选择器会失效
//                if (mFileUploadCallbackFirst != null) {
//                    mFileUploadCallbackFirst.onReceiveValue(null);
//                    mFileUploadCallbackFirst = null;
//                } else if (mFileUploadCallbackSecond != null) {
//                    mFileUploadCallbackSecond.onReceiveValue(null);
//                    mFileUploadCallbackSecond = null;
//                }
//            }
//        }
//    }


    @Override
    protected void resultPhotoPath(ImageView imageView, String s) {
        Log.e(TAG, "s", s);
        upicAsyPost.file = new File(s);
        upicAsyPost.execute(this);
    }


    @Override
    protected AppCrop getCrop() {
        return new AppCrop().setCrop(true);
    }


    @Override
    public void onButtonClick(View view) {
//        switch (view.getId()) {
//            case R.id.btn_showPopupWindow:
////                Intent i = new Intent(Intent.ACTION_PICK);
////                i.setType(mUploadableFileTypes);
////                startActivityForResult(i, REQUEST_CODE_FILE_PICKER);
//                startAlbum(null);
//                break;
//        }
    }

    /**
     * http://ask.csdn.net/questions/293 参考网页
     * 把content开头的文件，得到其实际路径
     *
     * @param contentUri
     * @return
     * @author hemiy
     */
    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }


//    // 初始化PopupWindow
//    private void initPw() {
//        if (popWindow == null) {
//            View pView = initPopWindow(R.layout.pw_selectbz);
//            popWindow.setWidth(getDisplayWidthHeight()[0] >> 1);
//            popWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//
//            View cancel = pView.findViewById(R.id.tv_cancel);
//            cancel.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    popWindow.dismiss();
//                }
//            });
//        }
//    }
//
//    // 弹出PopupWindow
//    private void showPw() {
//        if (popWindow == null)
//            return;
//        popWindow.showAsDropDown(findViewById(R.id.btn_showPopupWindow), 100, 100);
//
//        // 背景变暗
//        blurredBackground(0.7f);
//    }

}